<?php
namespace Common\Controller;

use Think\Auth;
use Think\Controller;
use Think\Page;

class HomeController extends Controller
{
    protected $where = array();
    protected $order = 'create_time desc';
    protected $listRows = 8;
    protected $auth = '';

    /**
     * 对请求进行验证
     * @author Alien
     * @return string
     */
    public function _initialize()
    {
        if(!session('id'))
        {
            $url = U('Login/index');
            echo "<script>parent.location.href = '{$url}' </script>";
            exit;
        }
        $auth = new Auth();
        $this->auth = $auth;
        $this->assign('auth',$auth);
    }

    /**
     * 数据列表
     * @author
     * @return string
     */
    public function index($p=1)
    {
        $list = D(CONTROLLER_NAME)->relation(true)->where($this->where)->page($p,$this->listRows)->order($this->order)->select();
        $page = new Page(D(CONTROLLER_NAME)->where($this->where)->count(),$this->listRows);
        $this->assign('list',$list);
        $this->assign('page',$page->show());
        $this->display();
    }

    /**
     * 删除用户
     * @author Mr.Alien
     * @return string
     * @param $id int 记录id
     */
    public function del($id)
    {
        $res = M(CONTROLLER_NAME)->delete((int)$id);
        if($res === false){
            $this->error('删除失败');
        }else{
            $this->success('删除成功');
        }
    }

    /**
     * 添加数据
     * @author Mr.Alien
     * @return string
     */
    public function add()
    {
        $this->display('edit');
    }

    /**
     * 修改数据
     * @author Mr.Alien
     * @return string
     */
    public function edit($id)
    {
        $info = D(CONTROLLER_NAME)->relation(true)->find($id);
        $this->assign('info',$info);
        $this->display();
    }

    /**
     * 保存数据
     * @author Mr.Alien
     * @return string
     */
    public function save()
    {
        $data = I('post.');
        if($data['id']){
            $res = M(CONTROLLER_NAME)->save($data);
        }else{
            $res = M(CONTROLLER_NAME)->add($data);
        }
        if($res === false){
            $this->error('保存失败');
        }else{
            $this->success('保存成功');
        }
    }
}